<?php

namespace App\Handlers;

use Illuminate\Support\Facades\Redis;

class IotCardHandler
{
    protected static $user = ' xmrckj';
    protected static $key = 'Oe821920Lk';
    protected static $token = 'eG1yY2tqOk9lODIxOTIwTGs=';   //base64_encode('xmrckj:Oe821920Lk')
    protected static $header = 'Basic eG1yY2tqOk9lODIxOTIwTGs=';   //Basic认证

    public static function cardInfoCache($imsi, $field){
        $key = 'card_info_'.$imsi;
        $res = Redis::get($key);
        if ($res) {
            $res = json_decode($res, true);
        } else {
            $res = self::cardInfoList(['imsi' => $imsi]);
            $res = reset($res);
            Redis::set($key, json_encode($res), 5);
            Redis::expire($key, 5); //只存在5秒
        }
        return $res[$field];
    }

    public static function cardInfo($iccid){
        $url = 'http://47.104.153.231:8100/cliapi/cardInfo';
        $data = ['iccid' => $iccid];
        return self::_curl($url, $data);
    }

    public static function cardInfoList($data = []){
        $url = 'http://47.104.153.231:8100/cliapi/cardInfoList';
        $res = self::_curl($url, $data);
        if ($res) {
            return $res['records'];
        } else {
            return false;
        }
    }

    public static function cardInfoPckList(){
        $url = 'http://47.104.153.231:8100/cliapi/pckList';
        $res = self::_curl($url, []);
        if ($res) {
            return $res['packages'];
        } else {
            return false;
        }
    }

    protected static function _curl($url, $data = []){
        if (!empty($data)) {
            $url .= '?'.http_build_query($data);
            // curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        $header = [
            'Content-type: application/json;charset=UTF-8',
            'Authorization: '.self::$header
        ];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $output = curl_exec($ch);
        $httpCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        curl_close($ch);
        $res = json_decode($output,true);
// error_log("res = ".print_r($res,1)."\n",3,'/tmp/joker.log');
        if ($httpCode == 200) {
            return $res;
        } else {
            return false;
        }
    }
}